package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RequestMapping("/dish")
@RestController
@Slf4j
public class DishController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /**
     * 菜品管理分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        // 构造分页构造器
        Page<Dish> page1 = new Page<>(page, pageSize);
        Page<DishDto> page2 = new Page<>();
        //        // 创造条件搜索构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getCreateTime);
        // 执行分页
        dishService.page(page1, lqw);
        BeanUtils.copyProperties(page1, page2, "records");
        List<Dish> records = page1.getRecords();
        List<DishDto> list = records.stream().map((rec) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(rec, dishDto);
            Long categoryId = rec.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String name1 = category.getName();
                dishDto.setCategoryName(name1);

            }

            return dishDto;
        }).collect(Collectors.toList());
        page2.setRecords(list);
        return R.success(page2);
    }

    /**
     * 套餐管理中的添加菜品
     * 用redis存取
     *
     * @param dish
     * @return
     */

    @GetMapping("/list")
    public R<List<DishDto>> adddish(Dish dish) {
        List<DishDto> dishDtoList = null;
        //构造动态key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        // 获取redis中的对应的值
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        // 判断dishDtoList是否为null
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }
        // 如果不存在 查询数据库
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //设置categoryId
        lqw.eq(Dish::getCategoryId, dish.getCategoryId());
        // 添加状态码
        lqw.eq(Dish::getStatus, 1);
        //添加排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);
        List<Dish> lists = dishService.list(lqw);
        dishDtoList = lists.stream().map(list -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(list, dishDto);
            Long id = list.getId();
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list1 = dishFlavorService.list(lqw1);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());
        // 将查询到的结果设置到redis
        redisTemplate.opsForValue().set(key, dishDtoList, 180000, TimeUnit.MILLISECONDS);
        return R.success(dishDtoList);
    }

    /**
     * 修改菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> update(@PathVariable Long id) {
        String keys = "dish_*";
        // 删除redis
        redisTemplate.delete(keys);
        log.info("long id: {}", id);
        DishDto dishDto = dishService.updateByIdd(id);

        return R.success(dishDto);
    }

    /**
     * 未完
     * 保存修改
     */
    @PutMapping
    public R<String> upDateSave(@RequestBody DishDto dishDto) {
        dishService.upDateSave(dishDto);
        return R.success("保存成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> dele(@RequestParam List<Long> ids) {
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量起售停售
     *
     * @param ids
     * @param valvs
     * @return
     */
    @PostMapping("/status/{valvs}")
    public R<String> status(@RequestParam List<Long> ids, @PathVariable Integer valvs) {
        log.info("aaaaaaaaaaaaaaa:{}", valvs);
        List<Dish> dishes = dishService.listByIds(ids);
        List<Dish> list = dishes.stream().map(dish -> {
            dish.setStatus(valvs);
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(list);
        return R.success("修改成公");
    }
}
